package com.hw.nio.channel;



import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author 车宏伟
 * @date 2021/1/13 12:54
 * TCP收发消息
 */
public class ServerSocketChannelTest {

    /**
     * 服务端接收消息
     *
     * @throws IOException
     */
    @Test
    public void testServer() throws IOException {
        ServerSocketChannel open = ServerSocketChannel.open();
        open.bind(new InetSocketAddress(6688));

        while (true){
            handle(open.accept());
        }

    }


    public void handle(final SocketChannel socketChannel) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                while (true) {
                    try {
                        buffer.clear();
                        socketChannel.read(buffer);
                        buffer.flip();
                        int i = 0;
                        byte[] arr = new byte[buffer.remaining()];
                        while (buffer.hasRemaining()) {
                            arr[i++] = buffer.get();
                        }
                        System.out.println(new String(arr));
                        buffer.rewind();
                        socketChannel.write(buffer);
                    } catch (Exception e) {
                        try {
                            socketChannel.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                }

            }
        }).start();
    }


}
